﻿using System;
using System.Text;
using MugenInjection.Infrastructure;
using MugenInjection.Interface;

namespace MugenInjection.Exceptions
{
    /// <summary>
    /// The exception that is thrown when found duplicate bindings.
    /// </summary>
#if !SILVERLIGHT
#if !NETFX_CORE
    [Serializable]
#endif
#endif
    public class ConflictBindingException : BindingException
    {
        #region Constructor

        /// <summary>
        /// Initializes a new instance of the <see cref="ConflictBindingException"/> class with a specified error message.
        /// </summary>
        /// <param name="bindingContext">Specifed <see cref="IBindingContext"/>.</param>
        /// <param name="isConverter"></param>
        public ConflictBindingException(IBindingContext bindingContext, bool isConverter = false)
            : base(FormatErrorMessage(bindingContext, isConverter))
        {
        }

        #endregion

        #region Methods

        private static string FormatErrorMessage(IBindingContext bindingContext, bool isConverter)
        {
            if (isConverter)
                return FormatConverterErrorMessage(bindingContext);
            return FormatBindingErrorMessage(bindingContext);
        }

        private static string FormatConverterErrorMessage(IBindingContext bindingContext)
        {
            var sb = new StringBuilder();
            sb.AppendLine(string.Format("More than one matching dynamic converters are available for a type {0}.", InjectorUtilsInternal.FormatType(bindingContext.Service)));
            sb.AppendLine(string.Format("Make sure you have registered only one dynamic converter(adapter or decorator) for {0} in a container.", InjectorUtilsInternal.FormatType(bindingContext.Service)));
            sb.AppendLine("The activation path:");
            sb.AppendLine(InjectorUtilsInternal.GetBuildPath(bindingContext));
            return sb.ToString();
        }

        private static string FormatBindingErrorMessage(IBindingContext bindingContext)
        {
            var sb = new StringBuilder();
            sb.AppendLine(string.Format("More than one matching bindings are available for a type {0}.", InjectorUtilsInternal.FormatType(bindingContext.Service)));
            sb.AppendLine(string.Format("Make sure you have registered only one binding for {0} in a container or set a higher priority.", InjectorUtilsInternal.FormatType(bindingContext.Service)));
            sb.AppendLine("The activation path:");
            sb.AppendLine(InjectorUtilsInternal.GetBuildPath(bindingContext));
            return sb.ToString();
        }

        #endregion
    }
}